import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/app/prisma/client';
import { writeFile } from 'fs/promises';
import { join } from 'path';
import { v4 as uuidv4 } from 'uuid';
import getUserId from '@/utils/getUserId';

export async function POST(req: NextRequest, { params }: { params: { groupId: string } }) {
  try {
    const operatorId = getUserId(req);
    if (!operatorId) {
      return NextResponse.json({ error: '请先登录' }, { status: 401 });
    }

    const { groupId } = params;

    // 1. 验证操作者是否为群主
    const group = await prisma.group.findUnique({ where: { id: groupId } });
    if (!group) {
        return NextResponse.json({ error: '群组不存在' }, { status: 404 });
    }
    if (group.ownerId !== operatorId) {
        return NextResponse.json({ error: '只有群主才能修改群组头像' }, { status: 403 });
    }

    const formData = await req.formData();
    const file = formData.get('file') as File | null;
    if (!file) {
      return NextResponse.json({ error: '没有提供文件' }, { status: 400 });
    }

    // 2. 保存文件
    const bytes = await file.arrayBuffer();
    const buffer = Buffer.from(bytes);
    const fileExtension = file.name.split('.').pop();
    const uniqueFilename = `${uuidv4()}.${fileExtension}`;
    const uploadDir = join(process.cwd(), 'public', 'uploads', 'avatars');
    const path = join(uploadDir, uniqueFilename);
    await writeFile(path, buffer);
    
    const baseUrl = process.env.BASE_URL || `http://localhost:${process.env.PORT || 8888}`;
    const avatarUrl = `${baseUrl}/uploads/avatars/${uniqueFilename}`;

    // 3. 直接更新群组的 avatar 字段
    const updatedGroup = await prisma.group.update({
      where: { id: groupId },
      data: { avatar: avatarUrl },
    });

    return NextResponse.json(updatedGroup, { status: 200 });
  } catch (error) {
    console.error('群组头像上传失败:', error);
    return NextResponse.json({ error: '服务器错误' }, { status: 500 });
  }
} 